import React, { Component } from 'react'
import { Modal, Radio, DatePicker, Tabs, Popover, Spin, Empty, Table, Button } from 'antd'
import echarts from 'echarts'
import moment from 'moment'
import 'moment/locale/zh-cn'
import uuid from 'uuid'

import request from '@/Utils/fecth'
import './index.less'
import { address } from '@/Utils/apiConfig'
const { organizationManagement: { monitor, statistic, blockSpeed }} = address
const { RangePicker } = DatePicker
const { TabPane } = Tabs

export default class Monitor extends Component {
  constructor(props) {
    super(props)
    this.state = {
      lidu: '1小时',
      key: '1',
      time: 24,
      pickerVisible: false,
      startTime: undefined, // 开始时间
      endTime: undefined, // 结束时间
      timeList: [
        // { id: "real", name: "实时" },
        { id: 24, name: '近24小时' },
        { id: 7, name: '近七天' },
        { id: 30, name: '近一月' },
        { id: 'choose', name: '选择日期' },
      ],
      netInList: [],
      netOutList: [],
      cpuList: [],
      memoryList: [],
      blockInList: [],
      blockOutList: [],
      statisticList: [],
      blockList: [],
    }
  }

  componentDidMount() {
    this.getMonitorData()
  }

  async getMonitorData(time = this.state.time) {
    let startTime = ''
    let endTime = moment(Date.now()).valueOf()
    switch (time) {
    case 24: {
      startTime = moment(Date.now()).add(-1, 'days').valueOf()
      break
    }
    case 7: {
      startTime = moment(Date.now()).add(-7, 'days').valueOf()
      break
    }
    case 30: {
      startTime = moment(Date.now()).add(-30, 'days').valueOf()
      break
    }
    default: {
      startTime = this.state.startTime ? moment(this.state.startTime) : ''
      endTime = this.state.endTime ? moment(this.state.endTime) : ''
    }
    }
    this.getData({
      startTime,
      endTime,
    })
  }

  async getData(params = {}) {
    const { key } = this.state
    if (['statistic'].includes(key)) {
      this.getStatistic(params)
      return false
    }
    if (['blockspeed'].includes(key)) {
      this.getBlockSpeed(params)
      return false
    }
    const type = ['net', 'cpu', 'memory', 'disk'][+key - 1]
    this.setState({
      loading: true,
    })
    let res = await request().get(monitor, {
      params: {
        type,
        containerName: this.props.peerData.domain,
        step: this.state.lidu === '1小时' ? 1 : 24, // 粒度
        ...params,
      },
    })
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      const data = res.data || {}
      Object.keys(data).forEach(key => {
        const value = data[key]
        const arr = value.map(v => {
          return {
            date: moment(v[0]).format(formatString),
            amount: +(parseFloat(v[1]).toFixed(2)),
          }
        })
        data[key] = arr
      })
      this.setState({
        netInList: data.net_i_usage || [],
        netOutList: data.net_o_usage || [],
        cpuList: data.cpu_usage || [],
        memoryList: data.memory_usage || [],
        blockInList: data.block_i_usage || [],
      }, this.initChart)
    }
  }

  getStatistic = async(params) => {
    const { peerData: { domain }} = this.props
    this.setState({
      loading: true,
    })
    const { startTime, endTime } = params
    const { status, data } = await request().get(statistic, {
      params: {
        domain,
        pageSize: 100,
        startTime: startTime ? moment(startTime).format(formatString) : '',
        endTime: endTime ? moment(endTime).format(formatString) : '',
      },
    })
    this.setState({
      loading: false,
    })
    if (status === 200) {
      this.setState({
        statisticList: (data.data || []).map(v => {
          return {
            ...v,
            uuid: uuid(),
          }
        }),
      })
    }
  }

  getBlockSpeed= async(params) => {
    const { peerData: { domain }} = this.props
    this.setState({
      loading: true,
    })
    const { startTime, endTime } = params
    const { status, data } = await request().get(blockSpeed, {
      params: {
        domain,
        pageSize: 100,
        step: this.state.lidu === '1小时' ? 1 : 24, // 粒度
        startTime: startTime ? moment(startTime).format(formatString) : '',
        endTime: endTime ? moment(endTime).format(formatString) : '',
      },
    })
    this.setState({
      loading: false,
    })
    if (status === 200) {
      this.setState({
        blockList: (data || []).map(v => {
          return {
            ...v,
            uuid: uuid(),
          }
        }),
      })
    }
  }

  initChart = () => {
    const { key, netInList, netOutList, cpuList, memoryList, blockInList } = this.state
    if (+key === 1) {
      this.initEcharts(netInList, `J_trend${key}`, 'KB')
      this.initEcharts(netOutList, `J_lichu${key}`, 'KB')
    }
    if (+key === 2) {
      this.initEcharts(cpuList.map(v => {
        return {
          ...v,
          amount: 100 * v.amount,
        }
      }), `J_cpu${key}`, '%')
    }
    if (+key === 3) {
      this.initEcharts(memoryList, `J_neicun${key}`, 'MB')
    }
    if (+key === 4) {
      this.initEcharts(blockInList, `J_trend${key}`, 'KB')
    }
  }

  // 确定时间
  comfirmTime = () => {
    const { startTime, endTime } = this.state
    if (startTime && endTime) {
      this.getData({
        startTime: startTime.valueOf(),
        endTime: endTime.valueOf(),
      })
    }
    this.setState({
      pickerVisible: false,
    })
  }

  initEcharts = (dateList, id, bite) => {
    document.getElementById(id) && (this[id] = echarts.init(document.getElementById(id)))
    let trendOption = {
      backgroundColor: 'rgba(0,0,0,0)',
      tooltip: {
        show: true,
        textStyle: {
          color: 'rgba(23,30,45,0.45)',
          fontSize: 12,
          fontFamily: 'Helvetica Neue',
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: 'rgba(0,0,0,0)',
          },
          z: -1,
        },
        trigger: 'axis',
        position: 'bottom',
        extraCssText: 'box-shadow: 0px 2px 8px 0px rgba(0,0,0,0.15);border-radius: 3px;padding:8px 12px;line-height:20px;',
        backgroundColor: 'rgba(255, 255, 255, 1)',
        formatter: `<span>{b}</span><br/><span style="color:rgba(23,30,45,0.85);font-family:PingFangSC-Regular,PingFang SC,font-weight:400,padding-top:2px">{c}${bite}</span><br/><span style="padding-top:2px,color:rgba(23,30,45,0.25);font-family:PingFangSC-Regular,PingFang SC,font-weight:400">粒度：${this.state.lidu}</span>`, // 提示框显示内容,此处{b}表示各数据项名称，此项配置为默认显示项，{c}表示数据项的值，默认不显示，({d}%)表示数据项项占比，默认不显示。
      },
      grid: {
        bottom: 0,
        top: 9,
        left: 0,
        right: 4,
        containLabel: true,
      },
      calculable: true,
      xAxis: [
        {
          boundaryGap: false,
          axisLabel: {
            margin: 0,
            fontFamily: 'PingFangSC-Regular',
            fontWeight: 400,
            color: 'rgba(0,0,0,0)',
            fontSize: 10,
            lineHeight: 14,
          },
          splitLine: {
            show: false, // 网格线是否显示
          },
          axisLine: {
            lineStyle: {
              color: '#E9E9E9',
            },
          },
          axisTick: {
            show: false,
          },
          type: 'category',
          data: dateList.map(element => element.date),
        },
      ],
      yAxis: [
        {
          type: 'value',
          boundaryGap: false,
          splitLine: {
            show: true, // 网格线是否显示
            lineStyle: {
              type: 'dashed',
              color: '#E9E9E9', // 修改网格线颜色
            },
          },
          max: Math.max(...dateList.map(element => { return element.amount })),
          interval: Math.max(...dateList.map(element => { return element.amount })) / 2,
          axisTick: {
            show: false,
          },
          axisLabel: {
            margin: 4,
            color: 'rgba(23,30,45,0.15)',
            fontSize: 12,
          },
          axisLine: {
            symbolSize: [10, 200],
            lineStyle: {
              color: 'rgba(255,255,255,0)',
            },
          },
        },
      ],
      series: [
        {
          type: 'line',
          symbol: 'circle',
          symbolSize: 8,
          color: ['#1e9b88'],
          areaStyle: {
            color: '#d2ebe7', // fade(@primary-color, 20%)
          },
          label: {
            color: '#1e9b88',
          },
          itemStyle: {
            // normal: {
            //     color: 'rgba(0,146,255,0)',
            // },
            emphasis: {
              color: '#1e9b88',
              borderWidth: 2,
              borderColor: '#fff',
            }, //* **这个字段就是控制鼠标悬浮在圆点上面让整个圆填充满背景色，也可以更改边框颜色等！***
          },
          lineStyle: {
            color: '#1e9b88',
          },
          smooth: true,
          hoverAnimation: false,
          data: dateList.map(element => { return element.amount }),

        },
      ],
    }
    this[id] && this[id].setOption(trendOption)
  }

  onChange = (key) => {
    this.setState({
      key,
    }, this.getMonitorData)
  }

  settingTime = (value) => {
    const time = value.target.value
    this.setState({
      time,
    })
    if (time === 'choose') {
      this.setState({
        pickerVisible: true,
      })
    } else {
      this.getMonitorData(time)
    }
  }

  changeGranularity = (value) => {
    this.setState({
      lidu: value,
    }, this.getMonitorData)
  }

  render() {
    const { netInList, cpuList, memoryList, blockInList, statisticList, blockList } = this.state
    return (
      <Modal
        title="监控"
        visible={true}
        footer={null}
        // centered={true}
        onCancel={() => {
          this.props.onCancel && this.props.onCancel()
        }}
        className="monitor-modal"
        width={1044}>
        <div className="current-peer-info">
          <div className="peer-name">
            当前节点：{this.props.peerData.name}
          </div>
        </div>
        <div className="time">
          <div>
            <Radio.Group defaultValue={24} onChange={(value) => this.settingTime(value)}>
              {
                this.state.timeList.map(element => {
                  return (
                    element.id === 'choose'
                      ? <Popover
                        visible={this.state.pickerVisible}
                        onVisibleChange={(visible) => {
                          this.setState({ pickerVisible: visible })
                        }}
                        key={element.id} placement="bottomLeft" content={
                          <div className="time-modal">
                            <RangePicker
                              format={'YYYY/MM/DD HH:mm:ss'}
                              allowEmpty={[true, true]}
                              value={[this.state.startTime || '', this.state.endTime || '']}
                              onCalendarChange={(list, string) => {
                                this.setState({
                                  startTime: list ? list[0] : '',
                                  endTime: list ? list[1] : '',
                                })
                              }}
                              onChange={(list, string) => {
                                this.setState({
                                  startTime: list ? list[0] : '',
                                  endTime: list ? list[1] : '',
                                })
                              }}
                              suffixIcon={<img alt="" src={require('@/images/org/time.svg')} />}
                              showTime />
                            <div className="btns">
                              <Button onClick={() => {
                                this.setState({
                                  startTime: '',
                                  endTime: '',
                                  pickerVisible: false,
                                })
                              }}>
                                重置
                              </Button>
                              <Button type="primary" style={{ marginLeft: '16px' }} onClick={() => this.comfirmTime()}>
                                确定
                              </Button>
                            </div>
                          </div>
                        } trigger="click">
                        <Radio.Button value={element.id}>
                          {element.name}
                          <img
                            alt=""
                            src={this.state.time === 'choose' ? require('@/images/org/dates.svg') : require('@/images/org/date.svg')}
                            style={{ marginTop: -2, marginLeft: 5 }}
                          />
                        </Radio.Button>
                      </Popover>
                      : <Radio.Button value={element.id} key={element.id}>
                        {element.name}
                      </Radio.Button>
                  )
                })
              }
            </Radio.Group>
          </div>
          {
            !['statistic'].includes(this.state.key) &&
            <div className="lidu">
            时间粒度：
              <Radio.Group defaultValue="1小时" onChange={(event) => this.changeGranularity(event.target.value)}>
                {
                  [{ id: '1min', name: '1小时' }, { id: '1day', name: '1天' }].map(element => {
                    return (
                      <Radio.Button value={element.name} key={element.id}>{element.name}
                      </Radio.Button>
                    )
                  })
                }
              </Radio.Group>
            </div>
          }
        </div>
        <Spin spinning={this.state.loading}>
          <div className="charts">
            <Tabs defaultActiveKey="1" onChange={(key) => this.onChange(key)}>
              <TabPane tab="流量监控" key="1">
                <div className="echarts">
                  <div className="echarts-name">
                    流量监控
                  </div>
                  {
                    netInList.length > 0 ? <React.Fragment>
                      <div>
                        <div className="description-name">
                          Peer节点入流量
                        </div>
                        <div className="small-text">(KB)</div>
                        <div className="description-name" style={{ marginTop: 41 }}>
                          Peer节点出流量
                        </div>
                        <div className="small-text">(KB)</div>
                      </div>
                      <div style={{ flex: 1 }}>
                        <div id="J_trend1" style={{ height: 60, width: '100%' }}></div>
                        <div id="J_lichu1" style={{ height: 60, width: '100%', marginTop: 22 }}></div>
                      </div>
                    </React.Fragment>
                      : <Empty style={{ width: '100%' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                </div>
              </TabPane>
              <TabPane tab="CPU监控" key="2">
                <div className="echarts">
                  <div className="echarts-name">
                    CPU监控
                  </div>
                  {
                    cpuList.length > 0
                      ? <React.Fragment>
                        <div>
                          <div className="description-name">
                            Peer节点CPU 使用率
                          </div>
                          <div className="small-text">(%)</div>
                        </div>
                        <div style={{ flex: 1 }}>
                          <div id="J_cpu2" style={{ height: 60, width: '100%' }}>
                          </div>
                        </div>
                      </React.Fragment>
                      : <Empty style={{ width: '100%' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                </div>
              </TabPane>
              <TabPane tab="内存监控" key="3">
                <div className="echarts">
                  <div className="echarts-name">
                    内存监控
                  </div>
                  {
                    memoryList.length > 0 ? <React.Fragment>
                      <div>
                        <div className="description-name">
                          Peer节点内存 使用率
                        </div>
                        <div className="small-text">(%)</div>
                      </div>
                      <div style={{ flex: 1 }}>
                        <div id="J_neicun3" style={{ height: 60, width: '100%' }}>
                        </div>
                      </div>
                    </React.Fragment>
                      : <Empty style={{ width: '100%' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                </div>
              </TabPane>
              <TabPane tab="磁盘监控" key="4">
                <div className="echarts">
                  <div className="echarts-name">
                    磁盘监控
                  </div>
                  {
                    blockInList.length > 0 ? <React.Fragment>
                      <div>
                        <div className="description-name">
                          磁盘已用容量
                        </div>
                        <div className="small-text">(KB)</div>
                      </div>
                      <div style={{ flex: 1 }}>
                        <div id="J_trend4" style={{ height: 60, width: '100%' }}>
                        </div>
                      </div>
                    </React.Fragment>
                      : <Empty style={{ width: '100%' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                </div>
              </TabPane>
              <TabPane tab="节点交易情况" key="statistic">
                <div className="table-container" style={{ padding: '24px 0' }}>
                  <Table rowKey={'uuid'} dataSource={statisticList} columns={
                    [
                      {
                        title: 'ip',
                        dataIndex: 'ip',
                      },
                      {
                        title: '查询数量',
                        dataIndex: 'queryNum',
                      },
                      {
                        title: '调用数量',
                        dataIndex: 'invokeNum',
                      },
                    ]
                  } />
                </div>
              </TabPane>
              <TabPane tab="区块生成速度" key="blockspeed">
                <div className="table-container" style={{ padding: '24px 0' }}>
                  <Table rowKey={'uuid'} dataSource={blockList} columns={
                    [
                      {
                        title: '通道名称',
                        dataIndex: 'channelName',
                      },
                      {
                        title: '区块生成速度',
                        dataIndex: 'blockSpeed',
                        render: (v, record) => {
                          return v ? `${v}/${record.unit}` : 0
                        },
                      },
                      {
                        title: '交易速度',
                        dataIndex: 'txSpeed',
                        render: (v, record) => {
                          return v ? `${v}/${record.unit}` : 0
                        },
                      },
                    ]
                  } />
                </div>
              </TabPane>
            </Tabs>
          </div>
        </Spin >
      </Modal>
    )
  }
}

const formatString = 'YYYY-MM-DD HH:mm:ss'

